// VBConversions Note: VB project level imports
using System.Diagnostics;
using System;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data;
using System.Collections.Generic;
using Microsoft.VisualBasic.Compatibility;
using System.Linq;
// End of VB project level imports

using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.IO;

namespace 喷码数据生成工具
{
	public class ImportFromExcel
	{
		System.Data.DataTable RTable;
		public ImportFromExcel(System.Data.DataTable TableStruct)
		{
			TableStruct.Rows.Clear();
			RTable = TableStruct;
		}
		public void ReadFile(string FileName)
		{
			if (RTable == null)
			{
				throw (new Exception("未准备接收数据的结构表！"));
			}
			if (File.Exists(FileName) == false)
			{
				throw (new Exception("文件不存在，请重新选择数据文件！"));
			}
			Excel.Application app = new Excel.Application();
			Workbook wb = null;
			Worksheet ReadSheet = default(Worksheet);
			bool HasError = false;
			string ErrTxt = "";
			try
			{
				wb = app.Workbooks.Open(FileName);
				ReadSheet = wb.Sheets(1);
				int RowCount = System.Convert.ToInt32(ReadSheet.UsedRange.Rows.Count);
				int ColCount = System.Convert.ToInt32(ReadSheet.UsedRange.Columns.Count);
				for (var i = 1; i <= RowCount; i++)
				{
					DataRow DataRow = RTable.NewRow();
					try
					{
						DataRow[0] = i;
						for (var j = 1; j <= ColCount; j++)
						{
							DataRow[j] = ReadSheet.Cells(i, j).value;
						}
						RTable.Rows.Add(DataRow);
					}
					catch (Exception ex)
					{
						if (ErrTxt != "")
						{
							ErrTxt += "\r\n" + "行：" + System.Convert.ToString(i) + "【" + ex.Message + "】";
						}
						else
						{
							ErrTxt = "行：" + System.Convert.ToString(i) + "【" + ex.Message + "】";
						}
						HasError = true;
					}
				}
				wb.Close();
				app.Quit();
				if (HasError)
				{
					Interaction.MsgBox("导入结束，导入过程中有错误记录，请注意检查数据！" + "\r\n" + ErrTxt, MsgBoxStyle.Information, "提示");
				}
			}
			catch (Exception ex)
			{
				Interaction.MsgBox(ex.Message, (int) MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "读取错误");
				if (wb != null)
				{
					wb.Close();
				}
				app.Quit();
			}
		}
	}
	
}
